package jayesh.gps;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.xml.sax.helpers.ParserFactory;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.location.Address;
import android.location.Geocoder;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ParseException;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class gps extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES =1;//in Meters;
private static final long MINIMUM_TIME_BETWEEN_UPDATES=1000; //in Milliseconds;

public final String DATABASE_NAME = "atmDB";  
	protected LocationManager locationManager;
	private ListView list2;
	private Button btnsubmit;
	 public Spinner bank_dropdown,km_dropdown;
	 public TextView txtCurr_location;
	 public LinearLayout linear01;
	 public LinearLayout linear02;
	 public LinearLayout linear03;
	 public Location currentLocation,dest;
     public double currentLatitude;
     public double currentLongitude;
     public TextView addressText;
    
     
     
     @Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
                
         linear01=(LinearLayout)findViewById(R.id.linear01);
         linear02=(LinearLayout)findViewById(R.id.linear02);
         linear03=(LinearLayout)findViewById(R.id.linear03);

        list2 =(ListView)findViewById(R.id.list2);
        btnsubmit =(Button)findViewById(R.id.submit);
        bank_dropdown = (Spinner)findViewById(R.id.bank_selection);
        km_dropdown =(Spinner)findViewById(R.id.km_selection);
        addressText = (TextView)findViewById(R.id.addressText);
        txtCurr_location=(TextView)findViewById(R.id.txtCurr_location);
        
       /* add("UBI", "150ft. Ring Road Br., Yogiraj Infrastruture, Nakshatra-I, Amin Marg, 150 ft. Ring Road, Rajkot - 360005, Gujarat", "Rajkot",70.8,22.283333);
        add("UBI"," Kalavad Road Br., A-1, Giriraj Building, Harihar Society, Kalavad Road, Dist. Rajkot, Gujarat, Pin - 360 001.","Rajkot",70.771501,22.28572);
        
        add("SBI","Akash Complex, Kalawad Road, Rajkot, Gujarat - 360001.","Rajkot",70.781447,22.292149);
        add("SBI","Atmiya College, Rajkot Branch Post Bag No. 13 Rajkot, Rajkot, Gujarat - 360001.","Rajkot",70.766673,22.28179);
        add("SBI","Gondal Road, Rajkot - 360002.","Rajkot",70.799439,22.268417);		
       
        add("SBI","10Acres Mall, Polytechnic [Ahmedabad] Branch Ahmedabad, Ahmedabad, Gujarat - 380015.","Ahmedabad",72.566005,23.039568);
        add("SBI","Ahmedabad Cantt. Campus, A, Ahmedabad Cantt Branch Cantonment Campus Sadar Bazar Ahmedabad, Ahmedabad, Gujarat - 380003.","Ahmedabad",72.604029,23.075546);
        add("SBI","10Acres Mall, Polytechnic [Ahmedabad] Branch Ahmedabad, Ahmedabad, Gujarat - 380015.","Ahmedabad",72.566005,23.039568);
       */
        //add("ICICI","10Acres Mall, Polytechnic [Ahmedabad] Branch Ahmedabad, Ahmedabad, Gujarat - 380015.","Ahmedabad",72.566005,23.039568);
        //add("ICICI","10Acres Mall, Polytechnic [Ahmedabad] Branch Ahmedabad, Ahmedabad, Gujarat - 380015.","Ahmedabad",72.566005,23.039568);
        //add("ICICI","10Acres Mall, Polytechnic [Ahmedabad] Branch Ahmedabad, Ahmedabad, Gujarat - 380015.","Ahmedabad",72.566005,23.039568);
       
        addressText.setText("ready");
        txtCurr_location.setText("ready2");
        
        ArrayAdapter<CharSequence> adapterBank = ArrayAdapter.createFromResource(
        		this, R.array.bank_array, android.R.layout.simple_spinner_item);
        adapterBank.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        ArrayAdapter<CharSequence> adapterKm = ArrayAdapter.createFromResource(
        		this, R.array.km_array, android.R.layout.simple_spinner_item);
        adapterKm.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        bank_dropdown.setAdapter(adapterBank);
        km_dropdown.setAdapter(adapterKm);
       
        locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
       /* LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                updateLocation(location);
            }
            public void onStatusChanged(
                    String provider, int status, Bundle extras) {}
            public void onProviderEnabled(String provider) {}
            public void onProviderDisabled(String provider) {}
        };
*/
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5, 10,new MyLocationListener());
        
        btnsubmit.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
							
				String bank_selected = (String)bank_dropdown.getSelectedItem();
				String km_selected =(String)km_dropdown.getSelectedItem();
				//add_list(bank_selected,"Rajkot");        
		        showCurrentLocation(bank_selected,km_selected);
		      //getAddress(bank_selected);
		        linear01.setVisibility(View.GONE);
		        linear02.setVisibility(View.VISIBLE);
		        linear03.setVisibility(View.VISIBLE);
			}
		});
        
       
	}

	
	/*void updateLocation(Location location){
        currentLocation = location;
        currentLatitude = currentLocation.getLatitude();
        currentLongitude = currentLocation.getLongitude();
     txtCurr_location.setText("Your Current Position is:"+ currentLatitude + ", " + currentLongitude);
    }
	 */
	protected void showCurrentLocation(String bank_selected,String km_selected) {
		 
		currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		 if(currentLocation!=null){
			 
		 currentLatitude = currentLocation.getLatitude();//22.294194;
	     currentLongitude = currentLocation.getLongitude();// 70.790598;
	     txtCurr_location.setText("Your Current Position \nLatitude: "+ Double.toString(currentLatitude) + ",\n Longitude: " + Double.toString(currentLongitude));
	     String message =String.format("New Location \n Longitude :%1$s \n Latitude :%2$s",currentLongitude,currentLatitude);
	     Toast.makeText(gps.this,message,Toast.LENGTH_LONG).show();
			getAddress(bank_selected,km_selected);
		 }
		 else
		 {   currentLatitude = 22.294194;
		     currentLongitude = 70.790598;
		     currentLocation.setLatitude(currentLatitude);
		     currentLocation.setLongitude(currentLongitude);
		     txtCurr_location.setText("Your CurrentPosition \nLatitude: "+Double.toString(currentLatitude) + ",\n Longitude: " + Double.toString(currentLongitude));
		 	String message =String.format("New Location \n Longitude :%1$s \n Latitude :%2$s",currentLongitude,currentLatitude);
			Toast.makeText(gps.this,message,Toast.LENGTH_LONG).show();
			 getAddress(bank_selected,km_selected);
			 addressText.setText("No Location Found");
	    }    		
		}
	
	void getAddress(String bank_selected,String km_selected){
        try{
            Geocoder gcd = new Geocoder(this, Locale.getDefault());
            // List<Address> addresses = gcd.getFromLocationName("Rajkot", 1);     
             List<Address> addresses =  gcd.getFromLocation(22.2833453,70.79999999999995 ,1);
            //List<Address> addresses =  gcd.getFromLocation(currentLatitude, currentLongitude,1);
           
            if (addresses.size() > 0) {
            	String localCity =(String) addresses.get(0).getLocality();
                StringBuilder result = new StringBuilder();
                
                for(int i = 0; i < addresses.size(); i++){
                    Address address =  addresses.get(i);
                    int maxIndex = address.getMaxAddressLineIndex();
                    for (int x = 0; x <= maxIndex; x++ ){
                        result.append(address.getAddressLine(x));
                        result.append(",");
                    }               
                    result.append(",");
                    result.append(address.getPostalCode());
                    //result.append("\n\n");
                }
                addressText.setText("Current Address : "+result.toString());
                add_list(bank_selected,localCity,km_selected);
            }
        }
        catch(IOException ex){
            addressText.setText(ex.getMessage().toString());
            //currentLocation.setLatitude(currentLatitude);
            //currentLocation.setLongitude(currentLongitude);
            add_list(bank_selected,"Rajkot",km_selected);
            
        }
    }
	
	private	class MyLocationListener implements LocationListener{

		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			String message =String.format("New Location \n Longitude :%1$s \n Latitude :%2$s",location.getLongitude(),location.getLatitude());
			Toast.makeText(gps.this,message,Toast.LENGTH_LONG).show();
			//txtCurr_location.setText(message); 
			 currentLatitude = location.getLatitude();
		     currentLongitude = location.getLongitude();
		     txtCurr_location.setText("New Location  Position \nLatitude: "+ currentLatitude + ",\n Longitude: " + currentLongitude);
		}

		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			Toast.makeText(gps.this,"Provider turned off Gps.",Toast.LENGTH_LONG).show();
		}

		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			Toast.makeText(gps.this,"Provider Turned on Gps.",Toast.LENGTH_LONG).show();
		}

	
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			Toast.makeText(gps.this,"Provider Status Changed.",Toast.LENGTH_LONG).show();
		}
		
	}

	public void add_list(String bank,String localCity,String km){
		SQLiteDatabase myDB = this.openOrCreateDatabase(DefaultDBHelper.DATABASE_NAME, SQLiteDatabase.OPEN_READWRITE, null);
		final ArrayList<String> results = new ArrayList<String>();
		
		dest = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		try {
	        
	        
	         /* Create the Database (no Errors if it already exists) */
	                    // myDB = dbHelper.getWritableDatabase();
	                    // dbHelper.onCreate(myDB);
	          /*   myDB.execSQL("CREATE TABLE IF NOT EXISTS " 
		                          + DefaultDBHelper.ATMTABLE
		                          + " ("+DefaultDBHelper.KEY_ATM_ID +"integer primary key autoincrement," +
		                          		DefaultDBHelper.KEY_BANK_NAME+" VARCHAR," +
		                          		DefaultDBHelper.KEY_ATM_ADD+" VARCHAR," +
		                          		DefaultDBHelper.KEY_CITY+" VARCHAR" +
		                          		DefaultDBHelper.KEY_LONGI+" REAL," +
		                          		DefaultDBHelper.KEY_LATI+"REAL);");*/
	                            // -- openOrCreateDatabase(name, mode, factory)
	                    // myDB = dbHelper.getReadableDatabase();
	     
		
	     //String[] columns={DefaultDBHelper.KEY_BANK_NAME,DefaultDBHelper.KEY_ATM_ADD};
	     String sql ="SELECT "+DefaultDBHelper.KEY_BANK_NAME+","+DefaultDBHelper.KEY_ATM_ADD+","+DefaultDBHelper.KEY_LATI+","+DefaultDBHelper.KEY_LONGI+" FROM atmtable3 WHERE "+DefaultDBHelper.KEY_BANK_NAME +" = '"+(String)bank+"' AND "+DefaultDBHelper.KEY_CITY +" = '"+(String)localCity+"'"; 
	    // Cursor c = myDB.query("atmtable2",columns,null,null, DefaultDBHelper.KEY_BANK_NAME +" = '"+(String)bank+"'",null, null,null);
	     Cursor c = myDB.rawQuery(sql,null);
	     startManagingCursor(c);
	     int col  =c.getCount();
	     /* Check if our result was valid. */ 
	 if (c != null) {
	 
	     c.moveToFirst(); // it's very important to do this action otherwise your Cursor object did not get work
	     
	     int bankNameColumn = c.getColumnIndex(DefaultDBHelper.KEY_BANK_NAME); 
	     int AtmAddColumn = c.getColumnIndex(DefaultDBHelper.KEY_ATM_ADD);
	     int lat2=c.getColumnIndex(DefaultDBHelper.KEY_LATI);
	     int long2 = c.getColumnIndex(DefaultDBHelper.KEY_LONGI);
	     
	     
	      /* Check if at least one Result was returned. */ 
	      if (c.isFirst()) { 
	           int i = 0;

	           /* Loop through all Results */ 
	           do { 
	                i++; 
	                String bankName = c.getString(bankNameColumn); 
	                String atmAdd = c.getString(AtmAddColumn);
	                
	                dest.setLatitude(c.getDouble(lat2));
	                dest.setLongitude(c.getDouble(long2));
	                
	                double m = (Double.parseDouble(km)*1000);
	                c.moveToNext();
	                if(currentLocation.distanceTo(dest)<=m)
	            	  results.add("\t" + bankName + "\t|  " + currentLocation.distanceTo(dest) );//+atmAdd );
	              
	            	
	               //results.add("\t" + bankName + "\t|  " +atmAdd);
	           } while (i!=col); 
	      } 
	      list2.setAdapter(new ArrayAdapter<String>(this, R.layout.front_list, results));
	    
	      
	      
	 }    
	    } catch (SQLiteException e) { 
	  	  System.out.println(e);
	    } finally { 
	         if (myDB != null) 
	              myDB.close(); 
	    }
	 }
	
    public void add(String bankName,String atmAdd,String city,double longitude,double latitude){
	    	SQLiteDatabase myDB = this.openOrCreateDatabase(DATABASE_NAME, SQLiteDatabase.OPEN_READWRITE, null);
	    	@SuppressWarnings("unused")
			final ArrayList<String> results = new ArrayList<String>();
	        	try {
	    		
	        		myDB.execSQL("DROP TABLE IF EXISTS atmtable2");
	               /* Create the Database (no Errors if it already exists) s*/
	                          // myDB = dbHelper.getWritableDatabase();
	                          // dbHelper.onCreate(myDB);
	
	        		myDB.execSQL("Create table IF NOT EXISTS atmtable3 (_id integer primary key autoincrement,bankName VARCHAR,atmAdd VARCHAR,city VARCHAR,longitude REAL,latitude REAL);");
	                  myDB.execSQL("INSERT INTO atmtable3 " 
	                         // + DefaultDBHelper.ATMTABLE
	                          + " (bankName,atmAdd,city,longitude,latitude)" 
	                          + " VALUES ('"+bankName+"','"+atmAdd+"','"+city+"',"+longitude+","+latitude+");");
	    	         } catch (SQLiteException e) {
	                            	  System.out.println(e);
	                 } finally { 
	                      if (myDB != null) 
	                           myDB.close(); 
	                 }
	        	}                	



}